package com.asking.controller;

import com.asking.domain.User;
import com.asking.service.UserService;
import com.asking.vo.Result;
import com.asking.vo.ResultVo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: 宋定鑫
 * @Date: 2018/10/17 15:44
 */
@RestController
@RequestMapping("/user")
public class  UserController {

    @Resource
    private UserService userService;

    @PostMapping("/add")
    public ResponseEntity<Result> add(User user){
        try{
            Result add = userService.add(user);
                return new ResponseEntity<>(add, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>(new Result(500,"服务器异常"),HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    @PutMapping
    public ResponseEntity<Result> updateuser(User user){
            Result result = userService.updata(user);
            if (result.getStatus() == 200){
                return new ResponseEntity<>(result,HttpStatus.OK);
            }else {
                return new ResponseEntity<>(result,HttpStatus.INTERNAL_SERVER_ERROR);
            }
    }

    @GetMapping("/{id}")
    public ResponseEntity<Result> idUser(@PathVariable("id")Integer id){
        try {
            User user =userService.selectByUser(id);
            return new ResponseEntity<>(new Result(200,"",user),HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<>(new Result(500,""),HttpStatus.INTERNAL_SERVER_ERROR);

        }

    }
    @GetMapping("/findAll")
    public ResponseEntity<Result> findAll(Integer page,Integer rows){
        try {
            ResultVo all = userService.findAll(page,rows);
            return new ResponseEntity<>(new Result(200,"",all),HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<>(new Result(500,""),HttpStatus.INTERNAL_SERVER_ERROR);

        }

    }
    @DeleteMapping("/{id}")
    public ResponseEntity<Result> deleteidUser(@PathVariable("id")Integer id){
        try{
            userService.deleteidUser(id);
            return new ResponseEntity<>(new Result(204,"删除成功"),HttpStatus.NO_CONTENT);
        }catch(Exception e){
            e.printStackTrace();
            return new ResponseEntity<>(new Result(500,"删除失败"),HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }
}
